<template>
  <el-dialog title="新增角色" @close="closeHandler" :visible.sync="isShow" width="45%">
    <!-- 绘制表单 -->
    <el-form
      :model="formData"
      ref="form"
      :rules="formRules"
      label-width="120px"
      :inline="false"
      size="small"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="角色状态">
        <el-switch
          v-model="formData.state"
          active-text="启用"
          inactive-text="禁用"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          rows="4"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="onSubmit"
          >立即创建</el-button
        >
        <el-button size="small" @click="isShow = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { addRoleApi } from '@/api/role';
export default {
  data() {
    return {
      // 弹框控制变量
      isShow: false,
      // 表单数据变量
      formData: {
        name: "",
        description: "",
        state: 0, // 0 未启用 1 启用
      },
      // 表单验证规则
      formRules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        description: [{ required: true, message: "请输入", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 表单提交逻辑
    async onSubmit() {
      try {
        // 1.表单校验
        await this.$refs.form.validate();
        // 2. 整理数据
        // 3. 发起网络请求
        await addRoleApi(this.formData)
        // 4. 提示成功
        this.$message.success('添加成功')
        // 5. 关闭
        this.isShow = false
        // 6. 通知列表更新
        this.$emit('updateList')
      } catch (error) {
        console.log(error);
      }
    },
    // 关闭事件
    closeHandler(){
      // 表单重置
      this.formData = {
         name: "",
        description: "",
        state: 0, // 0 未启用 1 启用
      }
      // 移除校验
      this.$refs.form.clearValidate()
    }
  },
};
</script>
<style lang="scss" scoped></style>
